<template>
  <NotLoggedIn v-if="!isLoggedIn" page-content="查看关注动态" />
  <div v-else class="container">
    <!-- 关注用户横向滚动列表 - 只在有关注用户时显示 -->
    <div v-if="followedUsers.length > 0" class="followed-users-container">
      <div class="users-scroll">
        <div 
          v-for="user in followedUsers" 
          :key="user.followedID"
          :class="['user-item', { active: currentUserId === user.followedID }]"
          @click="selectUser(user.followedID)"
        >
          <img :src="user.avatar || defaultAvatar" class="user-avatar" />
          <span class="user-name">{{ user.username || '用户' + user.followedID }}</span>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 用户没有关注任何人的提示 -->
    <div v-else-if="followedUsers.length === 0" class="empty-state">
      <el-empty description="你还没有关注任何人" />
      <el-button type="primary" @click="goToDiscover">去发现用户</el-button>
    </div>

    <!-- 无文章提示 -->
    <div v-else-if="articleList.length === 0" class="empty-state">
      <el-empty description="暂无文章" />
    </div>

    <!-- 文章列表 -->
    <ul v-else class="trend-container">
      <li v-for="article in articleList" :key="article.articleID" class="trend-item">
        <a class="user-avatar" @click="goToUserProfile(article.authorID)">
          <img class="avatar-item" :src="article.authorAvatar || defaultAvatar" />
        </a>
        <div class="main">
          <div class="info">
            <div class="user-info">
              <a>{{ article.authorName || '用户' + article.authorID }}</a>
            </div>
            <div class="interaction-hint">
              <span>{{ formatTime(article.creationTime) }}</span>
            </div>
            <div class="interaction-content" @click="openArticleDetail(article.articleID)">
              {{ article.title }}
            </div>
            <div v-if="article.images && article.images.length > 0" class="interaction-imgs">
              <div 
                v-for="(img, index) in article.images.slice(0, 4)" 
                :key="index" 
                class="details-box"
                @click="openArticleDetail(article.articleID)"
              >
                <img :src="img.imageUrl" />
              </div>
            </div>
            <div class="interaction-footer">
              <div class="icon-item">
                <Star 
                  :class="{ 'active': article.isFavorited }"
                  style="width: 1em; height: 1em" 
                  @click="toggleFavorite(article)"
                />
                <span class="count">{{ article.favoriteCount || 0 }}</span>
              </div>
              <div class="icon-item" @click="openArticleDetail(article.articleID)">
                <ChatRound style="width: 1em; height: 1em" />
                <span class="count">{{ article.commentCount || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- 文章详情模态窗口 -->
    <div v-if="showArticleDetail" class="article-modal-overlay" @click.self="closeArticleDetail">
      <ArticleDetail 
        :article-id="currentArticleId" 
        @close="closeArticleDetail"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Star, ChatRound } from "@element-plus/icons-vue";
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { FollowRelationApi } from '@/api/FollowRelationApi.js';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';
import UserUtil from '@/utils/User/User.js';
import ArticleDetail from '@/components/ArticleDetail.vue';
import NotLoggedIn from '@/components/NotLoggedIn.vue';

const router = useRouter();
const loading = ref(true);
const followedUsers = ref([]);
const articleList = ref([]);
const currentUserId = ref(null);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 文章详情模态窗口状态
const showArticleDetail = ref(false);
const currentArticleId = ref(null);

// 收藏状态缓存
const favoriteCache = ref({});

// 添加登录状态检查
const isLoggedIn = ref(UserUtil.isLogin());

// 获取关注的用户列表
const fetchFollowedUsers = async () => {
  try {
    const userId = UserUtil.getUserId();
    if (!userId) {
      ElMessage.warning('请先登录');
      return;
    }

    const relations = await FollowRelationApi.getFollowRelationsByFollowerId(userId);
    
    // 获取每个被关注用户的详细信息
    const usersWithInfo = await Promise.all(
      relations.map(async (relation) => {
        try {
          const userInfo = await UserProfileApi.getUserInfo(relation.followedID);
          return {
            ...relation,
            username: userInfo.username,
            avatar: userInfo.headshot
          };
        } catch (error) {
          return {
            ...relation,
            username: '用户' + relation.followedID,
            avatar: defaultAvatar
          };
        }
      })
    );

    followedUsers.value = usersWithInfo;
    
    // 默认选中第一个用户
    if (usersWithInfo.length > 0) {
      selectUser(usersWithInfo[0].followedID);
    } else {
      loading.value = false;
    }
  } catch (error) {
    ElMessage.error('获取关注用户列表失败');
    console.error(error);
    loading.value = false;
  }
};

// 选择用户
const selectUser = async (userId) => {
  currentUserId.value = userId;
  await fetchUserArticles(userId);
};

// 获取用户文章列表
const fetchUserArticles = async (userId) => {
  loading.value = true;
  try {
    // 获取文章列表
    const articles = await UserProfileApi.viewPublishedArticles(userId);
    
    // 如果没有文章，直接返回空数组
    if (!articles || articles.length === 0) {
      articleList.value = [];
      loading.value = false;
      return;
    }
    
    // 为每篇文章获取图片和其他信息
    const articlesWithDetails = await Promise.all(
      articles.map(async (article) => {
        try {
          // 获取文章图片
          const images = await TravelNoteApi.getArticleImages(article.articleID);
          
          // 获取作者信息
          const authorInfo = await UserProfileApi.getUserInfo(article.authorID);
          
          // 获取收藏状态
          const favoriteInfo = await checkFavoriteStatus(article.articleID);
          
          return {
            ...article,
            images: images || [],
            authorName: authorInfo.username || `用户${article.authorID}`,
            authorAvatar: authorInfo.headshot || defaultAvatar,
            isFavorited: favoriteInfo.isFavorited,
            favoriteId: favoriteInfo.favoriteId
          };
        } catch (error) {
          console.error(`处理文章 ${article.articleID} 详情失败:`, error);
          return {
            ...article,
            images: [],
            authorName: `用户${article.authorID}`,
            authorAvatar: defaultAvatar,
            isFavorited: false,
            favoriteId: null
          };
        }
      })
    );

    articleList.value = articlesWithDetails;
  } catch (error) {
    console.error('获取文章列表失败:', error);
    ElMessage.error('获取文章列表失败');
    articleList.value = [];
  } finally {
    loading.value = false;
  }
};

// 检查收藏状态
const checkFavoriteStatus = async (articleId) => {
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 获取当前用户ID
  const userId = UserUtil.getUserId();
  if (!userId) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 生成缓存键
  const cacheKey = `${userId}-${articleId}`;
  
  // 如果缓存中已有该收藏状态，直接返回
  if (favoriteCache.value[cacheKey] !== undefined) {
    return favoriteCache.value[cacheKey];
  }
  
  try {
    // 调用API检查收藏状态
    const Json_result = await TravelNoteApi.getFavoriteId(userId, articleId);
    const result = JSON.parse(Json_result);
    
    // 缓存收藏状态和ID
    const favoriteInfo = {
      isFavorited: result.status === "success",
      favoriteId: result.status === "success" ? result.favoriteID : null
    };

    favoriteCache.value[cacheKey] = favoriteInfo;

    return favoriteInfo;
  } catch (error) {
    console.error(`获取收藏状态失败, 文章ID: ${articleId}`, error);
    return { isFavorited: false, favoriteId: null };
  }
};

// 切换收藏状态
const toggleFavorite = async (article) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    const currentUserId = UserUtil.getUserId();
    const articleId = article.articleID;
    const cacheKey = `${currentUserId}-${articleId}`;
    
    if (article.isFavorited) {
      // 已收藏，需要取消收藏
      // 尝试从缓存获取收藏ID
      let favoriteId = favoriteCache.value[cacheKey]?.favoriteId;
      
      if (!favoriteId) {
        // 如果缓存中没有收藏ID，则从API获取
        const response = await TravelNoteApi.getFavoriteId(currentUserId, articleId);
        
        // 解析JSON字符串响应
        let favoriteResult;
        try {
          // 如果响应已经是对象，则不需要解析
          if (typeof response === 'object') {
            favoriteResult = response;
          } else {
            favoriteResult = JSON.parse(response);
          }
        } catch (parseError) {
          console.error('解析收藏ID JSON失败:', parseError);
          ElMessage.error('获取收藏ID失败');
          return;
        }
        
        if (favoriteResult.status === 'success') {
          favoriteId = favoriteResult.favoriteID;
        } else {
          ElMessage.error('获取收藏ID失败');
          return;
        }
      }
      
      if (favoriteId) {
        // 使用收藏ID删除收藏记录
        await TravelNoteApi.deleteCollection(favoriteId);
        
        // 更新UI
        article.isFavorited = false;
        if (article.favoriteCount > 0) {
          article.favoriteCount--;
        }
        
        // 更新缓存
        favoriteCache.value[cacheKey] = { isFavorited: false, favoriteId: null };
        
        ElMessage.success('取消收藏成功');
      } else {
        ElMessage.error('收藏ID不存在，无法取消收藏');
      }
    } else {
      // 未收藏，需要添加收藏
      const createResult = await TravelNoteApi.collectTravelNote(articleId);
      
      // 从创建结果中获取收藏ID
      let newFavoriteId = null;
      if (createResult && createResult.favoriteID) {
        newFavoriteId = createResult.favoriteID;
      }
      
      // 更新UI
      article.isFavorited = true;
      article.favoriteCount = (article.favoriteCount || 0) + 1;
      
      // 更新缓存
      favoriteCache.value[cacheKey] = { isFavorited: true, favoriteId: newFavoriteId };
      
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error);
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间';
  
  const now = new Date();
  const time = new Date(timeStr);
  const diff = Math.floor((now - time) / 1000);
  
  if (diff < 60) return '刚刚';
  if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
  if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
  if (diff < 2592000) return Math.floor(diff / 86400) + '天前';
  return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}`;
};

// 跳转到用户主页
const goToUserProfile = (userId) => {
  router.push({
    path: '/otherUser',
    query: { userId }
  });
};

// 跳转到发现页面
const goToDiscover = () => {
  router.push('/dashboard');
};

// 打开文章详情
const openArticleDetail = (articleId) => {
  currentArticleId.value = articleId;
  showArticleDetail.value = true;
  document.body.style.overflow = 'hidden';
};

// 关闭文章详情
const closeArticleDetail = () => {
  showArticleDetail.value = false;
  document.body.style.overflow = '';
};

onMounted(() => {
  fetchFollowedUsers();
});
</script>

<style lang="less" scoped>
.container {
  flex: 1;
  padding: 0 24px;
  width: 67%;
  margin: 0 auto;
  height: auto;
  min-height: calc(100vh - 72px);
  overflow: visible;
  position: relative;
  user-select: none;

  // 关注用户容器样式
  .followed-users-container {
    margin: 20px 0;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .users-scroll {
      display: flex;
      overflow-x: auto;
      gap: 16px;
      padding: 4px;
      
      &::-webkit-scrollbar {
        display: none;
      }

      .user-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        padding: 8px;
        border-radius: 8px;
        transition: all 0.3s;
        // 固定宽度
        width: 80px;
        flex-shrink: 0;

        &:hover {
          background: #f5f5f5;
        }

        &.active {
          background: #fff0f3;
          .user-name {
            color: #ff2442;
          }
        }

        .user-avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          margin-bottom: 8px;
          border: 2px solid transparent;
          object-fit: cover;
        }

        .user-name {
          font-size: 14px;
          color: #333;
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          text-align: center;
        }
      }
    }
  }

  // 加载容器样式
  .loading-container {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  // 空状态样式
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .el-button {
      margin-top: 16px;
    }
  }

  // 文章列表样式
  .trend-container {
    .trend-item {
      display: flex;
      flex-direction: row;
      padding-top: 24px;
      max-width: 100vw;

      .user-avatar {
        margin-right: 24px;
        flex-shrink: 0;

        .avatar-item {
          width: 48px;
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          border-radius: 100%;
          border: 1px solid rgba(0, 0, 0, 0.08);
          object-fit: cover;
        }
      }

      .main {
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        flex-direction: row;
        padding-bottom: 12px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.08);

        .info {
          flex-grow: 1;
          flex-shrink: 1;

          .user-info {
            display: flex;
            flex-direction: row;
            align-items: center;
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;

            a {
              color: #333;
            }
          }
          .interaction-hint {
            font-size: 14px;
            color: rgba(51, 51, 51, 0.6);
            margin-bottom: 8px;
          }
          .interaction-content {
            display: flex;
            font-size: 14px;
            color: #333;
            margin-bottom: 12px;
            line-height: 140%;
            cursor: pointer;
          }

          .interaction-imgs {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            
            .details-box {
              width: calc(25% - 6px);
              border-radius: 4px;
              margin-bottom: 8px;
              cursor: pointer;

              img {
                width: 100%;
                height: 150px;
                display: flex;
                border-radius: 4px;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                border: 1px solid rgba(0, 0, 0, 0.08);
                object-fit: cover;
              }
            }
          }

          .interaction-footer {
            margin: 8px 12px 0 0;
            padding: 0 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .icon-item {
              display: flex;
              justify-content: left;
              align-items: center;
              color: rgba(51, 51, 51, 0.929);
              cursor: pointer;
              
              &:hover {
                color: #ff2442;
              }
              
              .count {
                margin-left: 3px;
              }
              
              // 收藏状态激活样式
              .active {
                color: #ff2442;
              }
            }
          }
        }
      }
    }
  }
}

// 文章详情模态窗口样式
.article-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}
</style>
